'''
@author: saaj
@license: LGPL
'''


import logging

import cherrypy
import qxcpjsonrpc as rpc

import model


class Service(rpc.JsonRpcService):

  def onException(self, ex):
    entry = "{0}.{1}".format(self.__class__.__name__, ex.__class__.__name__)
    cherrypy.log(entry, severity = logging.ERROR)
    

class Note(Service):
  
  _model = None
  
  
  def preDispatch(self, request):
    super(Note, self).preDispatch(request)
    
    self._model = model.Note()
    
  @rpc.public
  def count(self):
    return self._model.count()
  
  @rpc.public
  def range(self, left, right):
    return self._model.range(left, right)
  
  @rpc.public
  def create(self, item):
    return self._model.create(item["name"], item["comment"])
  
  @rpc.public
  def remove(self, id):
    return self._model.remove(id)
  
  
class File(Service):
  
  _model = None
  
  
  def preDispatch(self, request):
    super(File, self).preDispatch(request)
    
    self._model = model.File()
    
  @rpc.public
  def list(self):
    return self._model.list()
    
  @rpc.public
  def remove(self, name):
    self._model.remove(name)
  
  @rpc.public
  def upload(self):
    part = None
    for value in getattr(cherrypy.request.params, "values")():
      if isinstance(value, cherrypy._cpreqbody.Part):
        part = value
        break
    if not part:
      raise Exception("Nothing uploaded")
    
    self._model.put(part.filename, part.file)    
    
  @rpc.public
  def download(self, name):
    cherrypy.response.headers["content-type"]        = "application/octet-stream"
    cherrypy.response.headers["content-disposition"] = "attachment; filename={0}".format(name)
    
    return self._model.get(name)
